<?php

namespace app\common\model\Business;

use think\Model;

// 引入软删除的模型
use traits\model\SoftDelete;

class Business extends Model
{
    // 在模型内使用软删除
    use SoftDelete;

    // 设置软删除的字段更新的时间字段
    protected $deleteTime = 'deletetime';

    // 设置表名
    protected $name = 'business';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 设置时间戳字段名
    protected $createTime = 'createtime';

    // 设置不更新时间戳
    protected $updateTime = false;

    protected $append = [
        'avatar_text',
        'province_text',
        'city_text',
        'district_text',
        'gender_text',
        'hide_mobile_text',
        'gender_text',
        'deal_text',
        'auth_text'
    ];

    // 获取器
    public function getAvatarTextAttr($value, $data)
    {   
        $cdnurl = config('site.cdnurl');
        
        $avatar = isset($data['avatar']) ? $data['avatar'] : '';

        // 为空或文件不存在时给一个默认值
        if (empty($avatar) || !is_file('.' . $avatar)) {
            $avatar = "/assets/img/avatar.png";
        }

        return $cdnurl . $avatar;
    }

    // 省
    protected function getProvinceTextAttr($value, $data)
    {   
        $code = empty($data['province']) ? '' : trim($data['province']);

        return model('Region')->where(['code' => $code])->value('name');
    }

    // 市
    protected function getCityTextAttr($value, $data)
    {
        $code = empty($data['city']) ? '' : trim($data['city']);

        return model('Region')->where(['code' => $code])->value('name');
    }

    // 区
    protected function getDistrictTextAttr($value, $data)
    {
        $code = empty($data['district']) ? '' : trim($data['district']);

        return model('Region')->where(['code' => $code])->value('name');
    }

    protected function getGenderTextAttr($value, $data)
    {
        $map = ['保密', '男', '女'];

        $gender = isset($data['gender']) ? $data['gender'] : 0;

        return $map[$gender];
    }

    protected function getHideMobileTextAttr($value, $data){
        if(empty($data['mobile'])){
            return '';
        }

        return preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $data['mobile']);
    }

    protected function getDealTextAttr($value, $data)
    {
        $map = [
            '未成交',
            '已成交',
        ];

        $deal = isset($data['deal']) ? $data['deal'] : 0;

        return $map[$deal];
    }

    protected function getAuthTextAttr($value, $data){
        $map = [
            '未认证',
            '已认证',
        ];

        $auth = isset($data['auth']) ? $data['auth'] : 0;

        return $map[$auth];
    }

    public function source()
    {
        return $this->belongsTo('app\common\model\Business\Source', 'sourceid', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    // 连接管理员表
    public function admin(){
        return $this->belongsTo('app\admin\model\Admin', 'adminid', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
